package com.rong.boot.jdbc.autoconfigure;

import com.rong.boot.jdbc.datasource.MultiTenantDataSource;
import org.springframework.boot.autoconfigure.AutoConfigureBefore;
import org.springframework.boot.autoconfigure.condition.ConditionalOnClass;
import org.springframework.boot.autoconfigure.condition.ConditionalOnMissingBean;
import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
import org.springframework.boot.autoconfigure.jdbc.DataSourceAutoConfiguration;
import org.springframework.boot.autoconfigure.jdbc.DataSourceProperties;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

import javax.sql.DataSource;
import java.util.Properties;

@Configuration
@ConditionalOnClass({DataSource.class, MultiTenantDataSource.class})
@EnableConfigurationProperties({DataSourceProperties.class})
@AutoConfigureBefore({DataSourceAutoConfiguration.class})
public class MultiDataSourceAutoConfiguration {
    public MultiDataSourceAutoConfiguration() {
    }

    @Bean
    @ConditionalOnMissingBean({DataSource.class})
    @ConditionalOnProperty(
            name = {"spring.datasource.type"},
            havingValue = "com.rong.boot.jdbc.datasource.MultiTenantDataSource"
    )
    public MultiTenantDataSource getTenantDataSource(DataSourceProperties properties) {
        MultiTenantDataSource dataSource = new MultiTenantDataSource();
        dataSource.setUrl(properties.getUrl());
        dataSource.setUsername(properties.getUsername());
        dataSource.setPassword(properties.getPassword());
        dataSource.setDriverClassName(properties.determineDriverClassName());
        Properties conProps = dataSource.getConnectionProperties();
        if (conProps == null) {
            conProps = new Properties();
            dataSource.setConnectionProperties(conProps);
        }

        conProps.setProperty("prepareThreshold", "0");
        return dataSource;
    }
}
